package schedule;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MonthlySchedule implements PaymentSchedule {
	private final long ONE_DAY_MILLISCONDS = 25 * 60 * 60 * 1000;

	@Override
	public boolean isPayDate(Date date) {		
		return isLastDayOfMonth(date);
	}

	@Override
	public Date getPayPeriodStartDate(Date date) {
		SimpleDateFormat month = new SimpleDateFormat("M");
		int days = 0;
		while (month.format(date.getTime() + ONE_DAY_MILLISCONDS * (days - 1)) == month
				.format(date)) {
			days--;
		}
		return new Date(date.getTime() + ONE_DAY_MILLISCONDS * days);
	}

	@Override
	public String toString() {
		return "monthly";
	}

	/**
	 * Checks if a day is the last day of the month
	 * 
	 * @param date
	 *            The date to be checked
	 * @return true if it is the last day.
	 */
	private boolean isLastDayOfMonth(Date date) {
		
		Calendar cal;
		Calendar last;
		cal = Calendar.getInstance();
		last = Calendar.getInstance();
		cal.setTime(date);
		last.setTime(date);
		
		int lastDayOfMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
		last.set(Calendar.DAY_OF_MONTH, lastDayOfMonth);
		
		if(last.getTime().compareTo(cal.getTime()) == 0){
			return true;
		} else {
			return false;
		}
	}

}
